<template>
<div>
    <NavigationBar />
    <el-container class="app-container">
      <el-header class="header">
          <h1>我的订单</h1>
      </el-header>
      <el-main>
          <!-- 循环遍历 orders 数组，并为每个订单创建一个 div 元素 -->
          <el-card v-for="order in orders" :key="order.order_ID" class="order">
              <div slot="header" class="order-header">
                  <el-row>
                      <el-col :span="18">
                          <h3>订单编号: {{ order.order_ID }}</h3> <!-- 数据绑定显示订单编号 -->
                      </el-col>
                      <el-col :span="6" class="order-actions">
                        <el-button type="primary" @click="openEvaluateSellerDialog(order)" plain>评价商家</el-button>
                      </el-col>
                  </el-row>
              </div>
              <div class="order-info">
                <p>订单详情:</p>
                <ul class="dish-list">
                  <li v-for="dish in order.dishList" :key="dish.dish_ID" class="dish-item">
                    {{ dish.dish_name }} - ¥{{ dish.price }} x {{ dish.quantity }}
                    <el-button type="success" @click="openEvaluateDishDialog(dish, order.merchant_ID, order.order_ID)" plain>评价菜品</el-button>
                  </li>
                </ul>
                <p>点餐方式：{{ order.order_form }}</p>
                <p>订单状态: {{ order.order_status }}</p>
                <p>创建时间: {{ new Date(order.create_time).toLocaleString() }}</p>
              </div>
          </el-card>
          <el-empty v-if="orders.length === 0" description="没有订单记录"></el-empty>
      </el-main>

      <!-- 评价商家对话框 -->
      <el-dialog title="评价商家" v-model="evaluateSellerDialogVisible">
        <el-form :model="merchantReviewForm">  <!-- el-form：用于创建表单 -->
          <el-form-item label="评分" :label-width="formLabelWidth">
            <el-rate v-model="merchantReviewForm.rating" :max="5"></el-rate>
          </el-form-item>
          <el-form-item label="评论" :label-width="formLabelWidth">
            <el-input type="textarea" v-model="merchantReviewForm.comment"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">  <!-- slot="footer"：用于自定义对话框的底部内容 -->
          <el-button @click="evaluateSellerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitMerchantReview">提交</el-button>
        </div>
      </el-dialog>

      <!-- 评价菜品对话框 -->
      <el-dialog title="评价菜品" v-model="evaluateDishDialogVisible">
        <el-form :model="dishReviewForm"> <!-- el-form：用于创建表单 -->
          <el-form-item label="评分" :label-width="formLabelWidth">
            <el-rate v-model="dishReviewForm.rating" :max="5"></el-rate>
          </el-form-item>
          <el-form-item label="评论" :label-width="formLabelWidth">
            <el-input type="textarea" v-model="dishReviewForm.comment"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer"> <!-- slot="footer"：用于自定义对话框的底部内容 -->
          <el-button @click="evaluateDishDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitDishReview">提交</el-button>
        </div>
      </el-dialog>
    </el-container>
</div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useStore } from 'vuex';  // 用于访问 Vuex store 中的数据
import axios from '@/axios'
import NavigationBar from '@/components/NavigationBar.vue';

const store = useStore(); // 使用 useStore 函数获取 Vuex Store 实例
const orders = ref([]); // 定义一个响应式引用 orders，初始值为空数组，用于存储订单数据

const fetchOrders = async () => { // 定义一个异步函数 fetchOrders，用于获取订单数据
  const user_ID = store.state.user.id; // 从 Vuex Store 中获取当前用户的 ID
  if (user_ID) {
    try {
      const response = await axios.get(`/api/user/UserGetOrderlist?user_ID=${user_ID}`);
      orders.value = response.data; // 将响应数据赋值给 orders
      模拟数据
    } catch (error) {
      console.error('Error fetching orders:', error);
    }
  }
};

/* 用于控制评价商家对话框的显示和隐藏 */
const evaluateSellerDialogVisible = ref(false);  

/* 存储商家评价表单的数据 */
const merchantReviewForm = ref({
  rating: 0,  // 评分
  comment: '',  // 评论
  merchant_ID: null,  // 商家 ID
  order_ID: null,  // 订单 ID
  user_ID: store.state.user.id  // 用户 ID
});
const formLabelWidth = '80px';

/* 打开评价商家的对话框，并设置当前订单的商家ID */
const openEvaluateSellerDialog = (order) => {
  merchantReviewForm.value.rating = 0; // 重置评分
  merchantReviewForm.value.comment = ''; // 重置评论
  merchantReviewForm.value.merchant_ID = order.merchant_ID; // 设置商家 ID
  merchantReviewForm.value.order_ID = order.order_ID; // 设置订单 ID
  evaluateSellerDialogVisible.value = true; // 显示评价商家对话框
};

/* 异步函数：提交商家评价数据到后端 */
const submitMerchantReview = async () => {
  if (merchantReviewForm.value.rating === 0) {
    alert('评分不能为空');
    return;
  }
  try {
    const response = await axios.post('/api/user/merchantReview', merchantReviewForm.value);
    console.log('Merchant review submitted:', response.data);  // 如果请求成功，服务器返回的数据被输出到控制台，并且评价对话框被关闭
    evaluateSellerDialogVisible.value = false;
  } catch (error) {
    console.error('Error submitting merchant review:', error);
  }
};

/* 用于控制评价菜品对话框的显示和隐藏 */
const evaluateDishDialogVisible = ref(false);

/* 存储菜品评价表单的数据 */
const dishReviewForm = ref({
  rating: 0, // 评分
  comment: '', // 评论
  dish_ID: null, // 菜品 ID
  merchant_ID: null,  // 商家 ID
  order_ID: null,  // 订单 ID
  user_ID: store.state.user.id, // 用户 ID
});

/* 打开评价菜品的对话框，并设置当前菜品的ID */
const openEvaluateDishDialog = (dish, merchant_ID, orderID) => {
  dishReviewForm.value.rating = 0; // 重置评分
  dishReviewForm.value.comment = ''; // 重置评论
  dishReviewForm.value.dish_ID = dish.dish_ID; // 设置菜品 ID
  dishReviewForm.value.merchant_ID = merchant_ID; // 设置商家 ID
  dishReviewForm.value.order_ID = orderID; // 设置订单 ID
  evaluateDishDialogVisible.value = true; // 显示评价菜品对话框
};

/* 异步函数：提交菜品评价数据到后端 */
const submitDishReview = async () => {
  if (dishReviewForm.value.rating === 0) {
    alert('评分不能为空');
    return;
  }
  try {
    const response = await axios.post('/api/user/dishReview', dishReviewForm.value);
    console.log('Dish review submitted:', response.data); // 如果请求成功，服务器返回的数据被输出到控制台，并且评价对话框被关闭
    evaluateDishDialogVisible.value = false;
  } catch (error) {
    console.error('Error submitting dish review:', error);
  }
};

onMounted(() => {  // 使用 onMounted 钩子，在组件挂载时调用 fetchOrders 函数
  fetchOrders();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f9f9f9;
}

.header {
  background-color: #ffffff;
  padding: 20px;
  border-bottom: 1px solid #ddd;
}

.header h1 {
  margin: 0;
  font-size: 28px;
  color: #333;
}

.order {
  border: 1px solid #ddd;
  padding: 15px;
  margin-bottom: 15px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.order-info {
  padding: 10px 0;
  font-size: 16px;
  color: #666;
}

.dish-list {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.dish-item {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  margin-bottom: 5px;
  border-bottom: 1px solid #eee;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
}

.order-actions .el-button {
  margin-left: 10px;
}

.el-empty {
  margin-top: 50px;
  text-align: center;
}
</style>
